import { defineStore } from 'pinia';
import { reactive } from 'vue';
import { useCargoStore } from './cargo';
import { type GameData } from '@/game/levelGameInfo';
import { useMapStore } from './map';
import { usePlayerStore } from './player';
import { useTargetStore } from './target';
interface Game {
  isGameCompleted: boolean;
  level: number;
}

export const useGameStore = defineStore('game', () => {
  const game = reactive<Game>({
    isGameCompleted: false,
    level: 1,
  });

  function detectionGameCompleted() {
    const { cargos } = useCargoStore();

    game.isGameCompleted = cargos.every((item) => item.status);
  }

  let _gameData: GameData = [];

  function changeGameInfo() {
    const { cargos, map, player: newPlay, targets } = _gameData[game.level - 1];

    // 设置地图
    const { setupMap } = useMapStore();
    setupMap(map);

    // 设置用户
    const { player } = usePlayerStore();
    player.x = newPlay.x;
    player.y = newPlay.y;

    // 设置目标点
    const { createTarget, addTarget, clearAllTarget } = useTargetStore();
    clearAllTarget();
    targets.forEach((item) => addTarget(createTarget(item)));

    // 添加箱子
    const { createCargo, addCargo, clearAllCargo } = useCargoStore();
    clearAllCargo();
    cargos.forEach((item) => addCargo(createCargo(item)));
  }

  function setupGameInfo(levelGameData: GameData) {
    _gameData = levelGameData;
    changeGameInfo();
  }

  function toNextLevel() {
    game.isGameCompleted = false;
    game.level += 1;
    changeGameInfo();
  }

  return {
    detectionGameCompleted,
    game,
    toNextLevel,
    setupGameInfo,
  };
});
